﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using GdNet.WebFramework.Domain.ReferencesData;
using GdNet.WebFramework.Domain.System;

namespace GdNet.WebFramework.Domain.ContentManagement
{
    public partial class ContentItem : EntityHistory
    {
        private readonly IList<ContentPart> _parts = new List<ContentPart>();

        #region Properties

        public virtual string Name
        {
            get;
            set;
        }

        public virtual string Description
        {
            get;
            set;
        }

        public virtual string Keywords
        {
            get;
            set;
        }

        public virtual DataLine Culture
        {
            get;
            set;
        }

        public virtual ReadOnlyCollection<ContentPart> Parts
        {
            get { return new ReadOnlyCollection<ContentPart>(_parts); }
        }

        #endregion

        #region Methods

        public virtual ContentPart GetPart(Guid partId)
        {
            return _parts.FirstOrDefault(x => x.Id == partId);
        }

        public virtual ContentItem AddPart(ContentPart part)
        {
            if (_parts.Contains(part) == false)
            {
                _parts.Add(part);
                part.ChangeRoot(this);
            }

            return this;
        }

        public virtual ContentItem RemovePart(ContentPart part)
        {
            if (_parts.Contains(part))
            {
                _parts.Remove(part);
            }

            return this;
        }

        public virtual ContentItem RemovePartById(Guid partId)
        {
            var contentPart = GetPart(partId);
            return RemovePart(contentPart);
        }

        public virtual ContentItem MoveUpPartById(Guid partId)
        {
            MovePartById(partId, true);
            return this;
        }

        public virtual ContentItem MoveDownPartById(Guid partId)
        {
            MovePartById(partId, false);
            return this;
        }

        private void MovePartById(Guid partId, bool isUp)
        {
            if (_parts.Count <= 1)
            {
                return;
            }

            var contentPart = GetPart(partId);
            if (contentPart == null)
            {
                return;
            }

            var index = _parts.IndexOf(contentPart);
            if (isUp && index > 0)
            {
                _parts.Remove(contentPart);
                _parts.Insert(index - 1, contentPart);
            }
            else if (index < _parts.Count - 1)
            {
                _parts.Remove(contentPart);
                _parts.Insert(index + 1, contentPart);
            }
        }

        #endregion
    }
}
